package com.example.demo.service.impl;

import com.example.demo.entity.Permission;
import com.example.demo.entity.Role;
import com.example.demo.entity.User;
import com.example.demo.repository.RoleRepository;
import com.example.demo.repository.UserRepository;
import com.example.demo.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
@Transactional
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RoleRepository roleRepository;

    /**
     * 根据用户名查询用户
     * @param name
     * @return
     */
    @Override
    public User findByName(String name) {

        return userRepository.findByName(name);
    }

    /**
     * 添加用户
     * @param map
     * @return
     */
    @Override
    public User addUser(Map<String, Object> map) {
        User user = new User();
        user.setName(map.get("username").toString());
        user.setPassword(map.get("password").toString());
        userRepository.save(user);
        return user;
    }

    /**
     * 添加角色
     * @param map
     * @return
     */
    @Override
    public Role addRole(Map<String,Object> map) {
       Optional<User> user = userRepository.findById(Long.valueOf(map.get("userId").toString()));
       Role role = new Role();
       role.setRoleName(map.get("roleName").toString());
       role.setUser(user.get());
        Permission permission1 = new Permission();
        permission1.setPermission("create");
        permission1.setRole(role);
        Permission permission2 = new Permission();
        permission2.setRole(role);
        permission1.setPermission("update");
        List<Permission> list = new ArrayList<>();
        list.add(permission1);
        list.add(permission2);
        role.setPermissions(list);
         return role;
    }
}
